from typing import Dict, List, cast
from nicegui import ui


async def get_filtered_data(grid: ui.aggrid):
    result = await grid.client.run_javascript(
        f"""
        const rowData = [];
        getElement({grid.id}).gridOptions.api.forEachNodeAfterFilter(node => rowData.push(node.data));
        return rowData;
    """
    )
    return cast(List[Dict], result)


async def get_data():
    rows = await get_filtered_data(aggrid)
    ui.notify(rows)


with ui.column().style("width: 300px"):
    columns = [{"field": "姓名"}, {"field": "电话"}]
    rows = [{"姓名": "A", "电话": "111"}, {"姓名": "B", "电话": "222"}]
    ui.button(
        icon="download",
        on_click=get_data,
    ).style("padding: 5px")

    aggrid = ui.aggrid(
        {
            "defaultColDef": {
                "flex": 1,
                "resizable": True,
                "floatingFilter": True,
                "filter": "agTextColumnFilter",
                "sortable": True,
                "editable": False,
                "minWidth": 150,
            },
            "columnDefs": columns,
            "rowData": rows,
            "rowSelection": "multiple",
            "stopEditingWhenCellsLoseFocus": True,
            "multiSortKey": "ctrl",
            "suppressDragLeaveHidesColumns": True,
        }
    ).classes("max-h-40")
    aggrid.options["pagination"] = False

ui.run()
